<template>
  <n-card class="department-list" title="组织架构" segmented>
    <n-tree
      v-model:selected-keys="selectedKeys"
      :data="treeData"
      :node-props="nodeProps"
      :cancelable="false"
      block-line
      default-expand-all
      key-field="id"
      label-field="name"
    />
  </n-card>
</template>

<script lang="ts" setup>
import { type DepartmentItem, getDepartmentList } from '@/api/sys/user'
import { deepTree, revDeepTree } from '@/utils'
import type { TreeOption } from 'naive-ui'

defineOptions({ name: 'DepartmentList' })

const emit = defineEmits(['refresh'])

// 树形数据
const treeData = ref<TreeOption[]>([])
// 选中项Id集合
const selectedKeys = ref<number[]>([])
watch(selectedKeys, (value) => {
  const item = console.log('selectedKeys ===', value)
})

function nodeProps({ option }: { option: TreeOption }) {
  return {
    onClick: () => rowClick(option),
    onContextmenu(e: Event) {
      e.preventDefault()
      console.log('onContextmenu ')
    },
  }
}

function rowClick(item?: TreeOption) {
  console.log('rowClick', item)

  if (item) {
    // 获取当前部门所有下级部门的Id集合
    const ids = item.children ? revDeepTree(item.children).map((e) => e.id) : []
    // 头部追加当前Id
    ids.unshift(item.id)

    // 触发自定义事件
    emit('refresh', { page: 1, departmentIds: ids })
  }
}

/** 刷新 */
async function refresh() {
  // 获取部门列表数据
  const data = await getDepartmentList()
  // 组转数据
  // const tmp = data.map((item) => ({ ...item, label: item.name, key: item.id }))
  // 转换树形，并赋值
  treeData.value = deepTree(data)
  selectedKeys.value = [data[0].id]
}

onMounted(() => {
  refresh()
})
</script>

<style lang="scss" scoped>
.department-list {
  .title {
  }
}
</style>
